/*
 * Created on 2004-8-4
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */

package cn.com.yinhex.as.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author test
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class XML2DOC
{
	public DOC[] read(String filename)
	{
		try
		{
			File file = new File(filename);
			FileInputStream fis = new FileInputStream(file);
			return parse(fis);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public DOC[] load(String str)
	{
		try
		{
			ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes("UTF-8"));
			return parse(bais);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public DOC[] parse(InputStream inputstream)
	{
		try
		{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(inputstream);
			//����doc
			NodeList eachDOC = document.getElementsByTagName("doc");
			if (eachDOC.getLength() == 0)
			{
				eachDOC = document.getElementsByTagName("row");
			}
			DOC[] docs = new DOC[eachDOC.getLength()];
			//����eachDoc�õ�ÿһ��DOC
			for (int i = 0; i < docs.length; i++)
			{
				NodeList oneDOC = eachDOC.item(i).getChildNodes();
				docs[i] = new DOC(oneDOC.getLength());
				for (int j = 0; j < oneDOC.getLength(); j++)
				{
					try
					{
						Node node = oneDOC.item(j);
						if (StringUtil.isFine(node.toString()))
						{
							if (node.toString().indexOf("<object") > -1)
							{
								String key = node.getAttributes().getNamedItem("key")
										.getNodeValue();
								String value = node.getFirstChild().getNodeValue();
								docs[i].put(key, value);
							}
							else
							{
								String key = node.getNodeName();
								String value = node.getFirstChild().getNodeValue();
								//System.out.println(key + " >> " + value);
								docs[i].put(key, value);
							}
						}
					}
					catch (Exception e)
					{
						//e.printStackTrace();
					}
				}
			}
			return docs;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
}